﻿using Api.FilesManage.App_Start;
using Common.Model;
using Document.Library;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Threading.Tasks;

namespace Api.FilesManage.Areas.Files.Controllers
{

    /// <summary>
    ///长连接相关逻辑
    /// </summary>
    public class FilesChatHub : BaseHub
    {
        /// <summary>
        /// 文件转码
        /// </summary>
        /// <param name="folderPath">文件夹名称</param>
        /// <param name="sourceFile">源文件</param>
        /// <param name="targetFile">转换后的文件</param>
        /// <param name="size">文件大小</param>
        /// <returns></returns>
        public void FileEscape(string folderPath, string sourceFile, string targetFile,double size)
        {
            var resultInfo = new ResultJsonInfo<decimal>();
            TryCatch(() =>
            {
                VideoRecodeData videoRecodeData = new VideoRecodeData
                {
                    BasePath = folderPath,
                    SourceFile = sourceFile,//源文件
                    TargetFile = targetFile,//转换后的文件
                    //VideoSize = "640x480",//视频分辨率
                    //BitRate_Video = "768"//视频比特率
                };
                VideoRecodeHelper _convert = new VideoRecodeHelper(videoRecodeData);

                _convert.OnResponse = (number) =>
                {
                    resultInfo.Data = Convert.ToDecimal(number);

                    resultInfo.Code = ActionCodes.InvalidOperation;
                    Clients.Client(Context.ConnectionId).SendAsync("FileEscapeMsg", resultInfo);
                };
                //结束事件
                _convert.OnEnd = (text) =>
                {
                    //删除文件
                    Task.Run(()=> {
                        FileHelper.FileRemove(folderPath, sourceFile);
                    });
                    resultInfo.Data = 1;
                    resultInfo.Code = ActionCodes.Success;
                    //由连接ID标识的特定客户端
                    Clients.Client(Context.ConnectionId).SendAsync("FileEscapeMsg", resultInfo);
                };
                _convert.Start();
            }, ex =>
            {
                resultInfo.SystemExc(resultInfo, ex, "文件转码失败");

            }, $"系统错误，文件服务-文件转码失败");
        }
    }
}
